/*************************导出xlsx格式文件 start*************************************/
//注意，需要有 /webapp/js/lib/xlsx.full.min.js 这个文件

//将一个json对象转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
//data:json数据，k/v类型，k是列数，v是内容
//columnNum:列数
//fileName:文件名
//sheetName:sheet名
function json_to_blob(data,columnNum,fileName, sheetName) {
    if($.isEmptyObject(data)){
        $.messager.alert("提示", "无数据", "info");
        return;
    }
    var table = document.createElement('table');//创建一个table对象。
    //通过循环的方式创建tr元素和td元素，然后对td元素进行赋值操作。
    $(data).each(function () {
        //设置内容
        var lRow = document.createElement('tr');  //创建tr
        for (let key=1;key<=columnNum;key++) {
            var tdText = document.createTextNode(this[key]);
            var td = document.createElement('td');
            td.appendChild(tdText);
            lRow.appendChild(td);      //td添加tr
        }
        table.appendChild(lRow);    //table添加tr
    });
    var sheet = XLSX.utils.table_to_sheet(table);//将一个table对象转换成一个sheet对象
    openDownloadDialog(sheet2blob(sheet, sheetName), fileName + '.xlsx');
}


//将table里的内容转成最终的excel文件blob对象，然后利用URL.createObjectURL下载
//id:标签的id
function btn_export(id, feilname, sheetName) {
    var table = document.querySelector("#" + id);
    var sheet = XLSX.utils.table_to_sheet(table);//将一个table对象转换成一个sheet对象
    openDownloadDialog(sheet2blob(sheet, sheetName), feilname + '.xlsx');
}

/**********************公用的方法*************************/
// 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
function sheet2blob(sheet, sheetName) {
    sheetName = sheetName || 'sheet1';
    var workbook = {
        SheetNames: [sheetName],
        Sheets: {}
    };
    workbook.Sheets[sheetName] = sheet; // 生成excel的配置项

    var wopts = {
        bookType: 'xlsx', // 要生成的文件类型
        bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        type: 'binary'
    };
    var wbout = XLSX.write(workbook, wopts);
    var blob = new Blob([s2ab(wbout)], {
        type: "application/octet-stream"
    }); // 字符串转ArrayBuffer
    function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }

    return blob;
}

function openDownloadDialog(url, saveName) {
    if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
    }
    var aLink = document.createElement('a');
    aLink.href = url;
    aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
    var event;
    if (window.MouseEvent) event = new MouseEvent('click');
    else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    }
    aLink.dispatchEvent(event);
}

/*************************导出xlsx格式文件 end*************************************/

/*************************xls案例，有bug *************************************/
function writeExcel(data, sheetName, fileName) {
    var uri = 'data:application/vnd.ms-excel;base64,'
        , tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
        + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>'
        + '<Styles>'
        + '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
        + '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
        + '</Styles>'
        + '{worksheets}</Workbook>'
        , tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
        , base64 = function (s) {
        return window.btoa(unescape(encodeURIComponent(s)))
    }
        , format = function (s, c) {
        return s.replace(/{(\w+)}/g, function (m, p) {
            return c[p];
        })
    };
    <!-- -->
    var ctx = "";
    var worksheetsXML = "";
    var rowsXML = "";
    for (var i = 0; i < 1; i++) {
        // 控制要导出的行数
        for (var j = 0; j <= data.length; j++) {
            rowsXML += '<Row>';
            //控制导出的列数（在本例中，最后一列为button,导出的文件会出错，所以导出到倒数第二列
            if (j == 0) {
                rowsXML += '<Cell><Data ss:Type="String">id</Data></Cell>';
                rowsXML += '<Cell><Data ss:Type="String">品类码</Data></Cell>';
                rowsXML += '<Cell><Data ss:Type="String">原始型号</Data></Cell>';
                rowsXML += '<Cell><Data ss:Type="String">网址</Data></Cell>';
                rowsXML += '<Cell><Data ss:Type="String">状态</Data></Cell>';
            } else {
                //第一行是目录
                rowsXML += '<Cell><Data ss:Type="String">' + data[j - 1].id + '</Data></Cell>';
                rowsXML += '<Cell><Data ss:Type="String">' + data[j - 1].categoryCode + '</Data></Cell>';
                rowsXML += '<Cell><Data ss:Type="String">' + data[j - 1].originalModel + '</Data></Cell>';
                rowsXML += '<Cell><Data ss:Type="String">' + data[j - 1].url + '</Data></Cell>';
                rowsXML += '<Cell><Data ss:Type="String">' + data[j - 1].entityStatus + '</Data></Cell>';
            }

            rowsXML += '</Row>';
        }
        ctx = {rows: rowsXML, nameWS: sheetName || 'Sheet' + i};
        worksheetsXML += format(tmplWorksheetXML, ctx);
        rowsXML = "";
    }

    ctx = {created: (new Date()).getTime(), worksheets: worksheetsXML};
    workbookXML = format(tmplWorkbookXML, ctx);

    //查看后台的打印输出
    // console.log(workbookXML);

    var link = document.createElement("A");
    link.href = uri + base64(workbookXML);
    link.download = fileName || '空型号.xls';
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}